package com.hefan.live.service;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.entity.ResultPojo;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.live.bean.LiveLog;
import com.hefan.live.bean.LiveRoom;
import com.hefan.live.bean.LivingHeartBeatVo;
import com.hefan.live.dao.LiveLogDao;
import com.hefan.live.dao.LiveRoomDao;
import com.hefan.live.itf.*;
import com.hefan.notify.itf.ItemsStaticService;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.WebUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.sql.Timestamp;
import java.util.Date;


/**
 * Created by nigle on 2016/10/17.
 */
@Path("/liveService")
@Component("liveStaticService")
public class LiveStaticServiceImpl implements LiveStaticService {
    public Logger logger = LoggerFactory.getLogger(LiveLogServiceImpl.class);

    @Resource
    LiveLogDao liveLogDao;
    @Resource
    LiveRoomDao liveRoomDao;
    @Resource
    WebUserService userService;
    @Resource
    LiveImOptService liveImOptlService;
    @Resource
    ItemsStaticService itemsStaticService;
    @Resource
    LiveLogService liveLogService;
    @Resource
    LiveLogPersonService liveLogPersonService;
    @Resource
    LivingRedisOptService livingRedisOptService;

    @GET
    @Path("/shutDown")
    @Override
    @Produces({ MediaType.APPLICATION_JSON })
    @Consumes({ MediaType.APPLICATION_JSON })
    public ResultPojo liveExcepEnd(@QueryParam("liveUuid") String liveUuid,@QueryParam("promptCopy") String  promptCopy){
        try {
            if(StringUtils.isBlank(liveUuid)){
                return new ResultPojo(ResultCode.ParamException);
            }
            LiveLog liveLog = liveLogDao.getLiveLogByUuid(liveUuid);
            if (null == liveLog) {
                return new ResultPojo(ResultCode.LiveIsNull);
            }
            LiveRoom liveRoom = liveRoomDao.getLiveRoomByUserId(liveLog.getUserId());
            //直播已经关闭或不存在
            if(null == liveRoom || liveRoom.getStatus() == GlobalConstants.AUTHOR_LIVEEND){
                return new ResultPojo(ResultCode.LiveIsEnd);
            }
            //关播流程
            Timestamp now_ = new Timestamp(new Date().getTime());
            WebUser user = userService.getWebUserInfoByUserId(liveLog.getUserId());
            if (null == user) {
                return new ResultPojo(ResultCode.UserNotFound);
            }
            //核准时长
            String infoRedis = null;
            try {
                infoRedis = livingRedisOptService.getLivingHeartBeatInfo(liveUuid);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (StringUtils.isNotBlank(infoRedis)) {
                LivingHeartBeatVo livingHeartBeatVo = JSON.parseObject(infoRedis, LivingHeartBeatVo.class);
                if (null != livingHeartBeatVo && livingHeartBeatVo.getChatRoomId() > 0
                        && StringUtils.isNotBlank(livingHeartBeatVo.getLiveUuid())
                        && StringUtils.isNotBlank(livingHeartBeatVo.getAuthoruserId())
                        && livingHeartBeatVo.getUpdateTime() > 0) {
                    Timestamp tt = new Timestamp(livingHeartBeatVo.getUpdateTime());
                    liveLog.setEndTime(tt);
                }
            }else {
                liveLog.setEndTime(liveLog.getStartTime());
            }
            //统计本次直播送礼记录,获取盒饭数据
            long liveLength = (liveLog.getEndTime().getTime() - liveLog.getStartTime().getTime())/1000;
            liveLog.setLiveLength(liveLength);
            liveLog.setValidLiveLength(liveLength);
            liveLog.setOptUser(1);//关闭来源,1表示来自后台关播
            liveLog.setAbnormal_end(GlobalConstants.ERR_LIVE_END);//异常关闭为1
            //观看人次
            long num = liveLog.getWatchNum();
            String watchNum = null;
            try {
                watchNum = livingRedisOptService.getLivingWatchNum(liveLog.getLiveUuid());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(StringUtils.isNotBlank(watchNum)){
                num = Long.valueOf(watchNum);
            }
            try {
                String addNUm = livingRedisOptService.getAddNumForRoom(liveLog.getUserId());
                if ( null != addNUm && Long.valueOf(addNUm) >= 0) {
                    num += Long.valueOf(addNUm);
                    logger.info("{}加入了{}额外人数",liveLog.getUserId(),addNUm);
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            liveLog.setWatchNum(num);

            //更新live_log和live_room
            try {
                liveLogService.liveEndMain(liveLog);
            }catch (Exception e){
                ResultPojo resultPojo = new ResultPojo();
                resultPojo.setCode(ResultCode.UNSUCCESS.get_code());
                resultPojo.setMsg("DB事务回滚，请重试");
                return resultPojo;
            }
            //异步处理更新直播间列表、红包、直播间观众
            liveLogService.liveEndAux(liveLog);

            //发送IM消息，发送三次
            liveImOptlService.liveBand(user,liveLog.getChatRoomId(), liveUuid,String.valueOf(num),String.valueOf(liveLog.getLiveLength()), String.valueOf(liveLog.getTicketCount()),promptCopy);
            liveImOptlService.liveBand(user,liveLog.getChatRoomId(), liveUuid,String.valueOf(num),String.valueOf(liveLog.getLiveLength()),String.valueOf(liveLog.getTicketCount()),promptCopy);
            liveImOptlService.liveBand(user,liveLog.getChatRoomId(), liveUuid,String.valueOf(num),String.valueOf(liveLog.getLiveLength()),String.valueOf(liveLog.getTicketCount()),promptCopy);

            //兼容ios老版本发直播间关闭im
            liveImOptlService.liveEndImAsync(user, liveLog.getChatRoomId(), liveUuid, String.valueOf(num), String.valueOf(liveLog.getLiveLength()), String.valueOf(liveLog.getTicketCount()));
            liveImOptlService.liveEndImAsync(user, liveLog.getChatRoomId(), liveUuid, String.valueOf(num), String.valueOf(liveLog.getLiveLength()), String.valueOf(liveLog.getTicketCount()));
            liveImOptlService.liveEndImAsync(user, liveLog.getChatRoomId(), liveUuid, String.valueOf(num), String.valueOf(liveLog.getLiveLength()), String.valueOf(liveLog.getTicketCount()));

            logger.info("后台关闭直播、禁播成功，liveUuid："+liveUuid);
            return new ResultPojo(ResultCode.SUCCESS);

        }catch (Exception e){
            logger.error("后台关闭直播失败",e);
            return new ResultPojo(ResultCode.UNSUCCESS);
        }
    }

    @GET
    @Path("/loginOut")
    @Override
    @Produces({ MediaType.APPLICATION_JSON })
    @Consumes({ MediaType.APPLICATION_JSON })
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
    public ResultPojo loginOutForBack(@QueryParam("userId") String userId)  {
        ResultBean rb = new ResultBean();
        try {
            if(StringUtils.isBlank(userId)){
                return new ResultPojo(ResultCode.ParamException);
            }
            WebUser user = userService.getWebUserInfoByIsDel(userId,2);
            if( null == user){
                return new ResultPojo(ResultCode.UserNotFound);
            }
            //如果在直播中，先关播
            if( user.getUserType() == GlobalConstants.USER_TYPE_STAR ||
                    user.getUserType() == GlobalConstants.USER_TYPE_SITE ||
                    user.getUserType() == GlobalConstants.USER_TYPE_FAMOUS){
                LiveRoom liveRoom = liveRoomDao.getLiveRoomByUserId(userId);
                if(liveRoom.getStatus() == GlobalConstants.AUTHOR_LIVING){
                    rb = liveEndForLoginOut(liveRoom.getLiveUuid());
                    if (null != rb && rb.getCode() != ResultCode.SUCCESS.get_code()) {
                        return new ResultPojo(ResultCode.UNSUCCESS);
                    }
                }
            }
            //发三遍跳出登录IM消息
            rb = liveImOptlService.userLoginOut(user);
            if (rb.getCode() != ResultCode.SUCCESS.get_code()) {
                rb = liveImOptlService.userLoginOut(user);
                if (rb.getCode() != ResultCode.SUCCESS.get_code()) {
                    liveImOptlService.userLoginOut(user);
                }
            }
            return new ResultPojo(ResultCode.SUCCESS);
        }catch (Exception e){
            logger.error("踢出登录私信发送失败",e);
            return new ResultPojo(ResultCode.UNSUCCESS);
        }
    }

    /**
     * 一键退出时，如果是主播正开播，关播处理，IM广播消息类型201
     * @param liveUuid
     * @return
     */
    private ResultBean liveEndForLoginOut(String liveUuid){
        try {
            LiveLog liveLog = liveLogDao.getLiveLogByUuid(liveUuid);
            LiveRoom liveRoom = liveRoomDao.getLiveRoomByUserId(liveLog.getUserId());
            Timestamp now_ = new Timestamp(new Date().getTime());
            WebUser user = userService.getWebUserInfoByUserId(liveLog.getUserId());
            if(null == liveRoom || null == liveLog || null == user ){
                logger.info("live_log 、 live_room、web_user数据查询失败");
                return new ResultBean(ResultCode.UNSUCCESS);
            }
            //核准时长
            String infoRedis = livingRedisOptService.getLivingHeartBeatInfo(liveUuid);
            if (StringUtils.isNotBlank(infoRedis)) {
                LivingHeartBeatVo livingHeartBeatVo = JSON.parseObject(infoRedis, LivingHeartBeatVo.class);
                if (null != livingHeartBeatVo && livingHeartBeatVo.getChatRoomId() > 0
                        && StringUtils.isNotBlank(livingHeartBeatVo.getLiveUuid())
                        && StringUtils.isNotBlank(livingHeartBeatVo.getAuthoruserId())
                        && livingHeartBeatVo.getUpdateTime() > 0) {
                    Timestamp tt = new Timestamp(livingHeartBeatVo.getUpdateTime());
                    liveLog.setEndTime(tt);
                }
            }else {
                liveLog.setEndTime(liveLog.getStartTime());
            }
            //统计本次直播送礼记录,获取盒饭数据
            Long liveLength = (liveLog.getEndTime().getTime() - liveLog.getStartTime().getTime())/1000;
            liveLog.setLiveLength(liveLength);
            liveLog.setValidLiveLength(liveLength);
            liveLog.setOptUser(1);//关闭来源,1表示来自后台关播
            liveLog.setAbnormal_end(GlobalConstants.ERR_LIVE_END);//异常关闭为1
            //观看人次
            long num = liveLog.getWatchNum();
            String watchNum = livingRedisOptService.getLivingWatchNum(liveLog.getLiveUuid());
            if(StringUtils.isNotBlank(watchNum)){ num = Long.valueOf(watchNum); }
            try {
                String addNUm = livingRedisOptService.getAddNumForRoom(liveLog.getUserId());
                if ( null != addNUm && Long.valueOf(addNUm) >= 0) {
                    num += Long.valueOf(addNUm);
                    logger.info("{}加入了{}额外人数",liveLog.getUserId(),addNUm);
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            liveLog.setWatchNum(num);
            //更新live_log和live_room
            try {
                liveLogService.liveEndMain(liveLog);
            }catch (Exception d){
                ResultPojo resultPojo = new ResultPojo();
                resultPojo.setCode(ResultCode.UNSUCCESS.get_code());
                resultPojo.setMsg("DB事务回滚，请重试");
                return new ResultBean(ResultCode.UNSUCCESS);
            }
            //异步处理更新直播间列表、红包、直播间观众
            liveLogService.liveEndAux(liveLog);
            //发送IM消息，发送三次
            liveImOptlService.liveEndIm(user,liveRoom.getChatRoomId(), liveUuid,String.valueOf(num),String.valueOf(liveLog.getLiveLength()), String.valueOf(liveLog.getTicketCount()));
            liveImOptlService.liveEndIm(user,liveLog.getChatRoomId(), liveUuid,String.valueOf(num),String.valueOf(liveLog.getLiveLength()),String.valueOf(liveLog.getTicketCount()));
            liveImOptlService.liveEndIm(user,liveLog.getChatRoomId(), liveUuid,String.valueOf(num),String.valueOf(liveLog.getLiveLength()),String.valueOf(liveLog.getTicketCount()));
            logger.info("一键退出登录后台关闭直播成功，liveUuid："+liveUuid);
            return new ResultBean(ResultCode.SUCCESS);
        }catch (Exception e){
            logger.error("一键退出登录后台关闭直播失败",e);
            return new ResultBean(ResultCode.UNSUCCESS);
        }
    }

    @GET
    @Path("/addCountForLiving")
    @Override
    @Produces({ MediaType.APPLICATION_JSON })
    @Consumes({ MediaType.APPLICATION_JSON })
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
    public ResultPojo addCountForLiving(@QueryParam("userId") String userId ,@QueryParam("number") long number)  {
        try {
            if(StringUtils.isBlank(userId) || number < 0){
                return new ResultPojo(ResultCode.ParamException);
            }
            String result = livingRedisOptService.setAddNumForRoom(userId, String.valueOf(number));
            logger.info("为{}添加{}额外人数，返回结果{}",userId,number,result);
            result = livingRedisOptService.getAddNumForRoom(userId);
            if (String.valueOf(number).equals(result)) {
                return new ResultPojo(ResultCode.SUCCESS);
            }else {
                logger.info("为{}添加{}额外人数失败",userId,number);
                return new ResultPojo(ResultCode.UNSUCCESS);
            }
        }catch (Exception e){
            logger.error("为{}添加{}额外人数失败",userId,number);
            e.printStackTrace();
            return new ResultPojo(ResultCode.UNSUCCESS);
        }
    }

    @GET
    @Path("/test")
    @Override
    @Produces({ MediaType.APPLICATION_JSON })
    @Consumes({ MediaType.APPLICATION_JSON })
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
    public void test(@QueryParam("a") String a,@QueryParam("b") String b)  {

    }
}
